package language;

import org.junit.Test;

import java.util.Date;
import java.util.Optional;

public class OptionalTest {

    @Test
    public void optionalUsage(){
        Optional<String> stringOptional = Optional.of("string");//如果存入的值是 null 则抛异常
        Optional<Object> empty = Optional.empty();  // 等价于Optional.ofNullable(null)

        stringOptional.isPresent(); //true
        stringOptional.ifPresent(System.out::println);

        String s = stringOptional.get(); //如果为empty，那么会报异常。这个函数应该不常用
        Object none = empty.orElse("None");
        Object o = empty.orElseGet(() -> new Date());

        try {
            empty.orElseThrow(() -> new RuntimeException());
        }catch(Exception e){
            System.out.println(e);
        }
    }
}
